using MediatR;
using B.S.XZYData.Api.Wrter.Application.Command.Route;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using SqlSugar;
using System.Linq;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Route
{
    public class AddRouteStepHandler : IRequestHandler<AddRouteStepCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RouteModel> _routeRepository;
        private readonly IBaseRepository<RouteStepModel> _routeStepRepository;

        public AddRouteStepHandler(IBaseRepository<RouteModel> routeRepository, IBaseRepository<RouteStepModel> routeStepRepository)
        {
            _routeRepository = routeRepository;
            _routeStepRepository = routeStepRepository;
        }

        public async Task<ApiResult<int>> Handle(AddRouteStepCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            
            try
            {
                // 检查工艺路线是否存在
                var routeExists = await _routeRepository.GetAll()
                    .Where(x => x.Id == request.RouteId)
                    .AnyAsync();
                if (!routeExists)
                {
                    res.Code = ApiEnum.Fail;
                    res.Msg = "工艺路线不存在";
                    return res;
                }

                // 删除该工艺路线原有的工序（如果存在）
                var existingSteps = await _routeStepRepository.GetAll()
                    .Where(x => x.RouteId == request.RouteId)
                    .ToListAsync();
                if (existingSteps.Any())
                {
                    await _routeStepRepository.DeleteBatchAsync(existingSteps);
                }

                int addedStepsCount = 0;
                
                // 添加新的工序步骤
                if (request.Steps != null && request.Steps.Any())
                {
                    var stepEntities = request.Steps.Select(step => new RouteStepModel
                    {
                        RouteId = request.RouteId,
                        Sequence = step.Sequence,
                        ProcessCode = step.ProcessCode,
                        ProcessName = step.ProcessName,
                        Ratio = step.Ratio,
                        Type = step.Type,
                        CreateBy = request.OperateBy,
                        CreateTime = DateTime.Now,
                        UpdateBy = request.OperateBy,
                        UpdateTime = DateTime.Now
                    }).ToList();

                    addedStepsCount = await _routeStepRepository.CreateBatchAsync(stepEntities);
                    if (addedStepsCount <= 0)
                    {
                        res.Code = ApiEnum.Error;
                        res.Msg = "添加工序失败";
                        return res;
                    }
                }

                res.Code = ApiEnum.Success;
                res.Msg = "添加工序成功";
                res.Data = addedStepsCount;
                return res;
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"添加工序异常：{ex.Message}";
                return res;
            }
        }
    }
} 